﻿/// <reference path="jquery-1.7.2-vsdoc.js" />
/// <reference path="knockout-2.1.0.js" />
/// <reference path="knockout.mapping-latest.js" />

var viewModel = function () {
    var self = this;

    self.loading = ko.observable(false);
    self.pageindex = ko.observable(0);
    self.totalItems = ko.observable(0)
    self.pagesize = ko.observable(20);
    self.items = ko.observableArray([])

    self.load = function (pageindex) {
        self.loading(true);
        self.items.removeAll();
        var index = pageindex == null ? 1 : pageindex;
        $.ajax({
            url: '/json/loadpeople/',
            data: { "id": index },
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                self.loading(false);
                ko.mapping.fromJS(result.Items, {}, self.items);
                self.totalItems(result.Total);
                self.pageindex(result.PageIndex);
            },
            error: function (jqXHR, textStatus) {
                self.loading(false);
                alert(textStatus);
            }
        });
    };

    self.pager = ko.computed(function(){ 
        return new pager(self.pageindex(), self.pagesize(), self.totalItems());
    });
    
    ko.bindingHandlers.pager = {
        init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            return { controlsDescendantBindings: true }; 
        },
        update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var v = ko.utils.unwrapObservable(valueAccessor());
            var _total = ko.utils.unwrapObservable(v.total);
            var _pageindex = ko.utils.unwrapObservable(v.pageindex);
            var _pagesize = ko.utils.unwrapObservable(v.pagesize);
            var _pager = ko.utils.unwrapObservable(v.pager);
            while (element.firstChild)
                ko.removeNode(element.firstChild);

            alert(_pager.pageindex);
            alert(_pager.pagesize);
            alert(_pager.totalItems);

            $('<span id="pager_total">').appendTo(element);
            $('#pager_total').html('всего: ' + _total);

            $('<span id="pager_pagesize">').appendTo(element);
            $('#pager_pagesize').html('на странице: ' + _pagesize);

            //var pagerLinks = element.appendChild(document.createElement("DIV"));
            
        }
    };
};

var pager = function (pageIndex, pageSize, totalItems) {
    var self = this;
    if (!totalItems) return;
    self.pages.removeAll();
    self.pageIndex = ko.observable(pageIndex);
    self.pageSize = ko.observable(pageSize);
    self.totalItems = ko.observable(totalItems);
    self.pages = ko.observableArray([]);
    self.totalPages = ko.computed(function () {
        var t = Math.ceil(self.totalItems() / self.pageSize());
        var itogo = t.isNaN ? 0 : t;
        if (itogo > 0) {
            for (var i = 1; i < itogo; i++) {
                self.pages.push(new pagerPage(i, pageIndex==i));
            }
        }
        return itogo;
    }, self);
};

var pagerPage = function (number, selected) {
    var self = this;
    self.pageNumber = number;
    self.selected = selected;
}

ko.bindingHandlers.date = {
    init:
        function (element, valueAccessor, allBindingsAccessor, viewModel) {
            var jsonDate = valueAccessor();
            var d = eval("new " + jsonDate().replace(/[\\/]/g, ""))
            var d00 = d.getDate();
            var m00 = d.getMonth() + 1;
            var dd = d00.toString().length == 2 ? d00 : '0' + d00;
            var mm = m00.toString().length == 2 ? m00 : '0' + m00;
            var ret = dd + "." + mm + "." + d.getFullYear();
            element.innerHTML = ret;
        },
    update:
        function (element, valueAccessor, allBindingsAccessor, viewModel) {
        }
};

//var templateEngine = new ko.nativeTemplateEngine();

//ko.

//templateEngine.addTemplate = function (templateName, templateMarkup) {
//    document.write("<script type=\"text/html\" id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
//};

//templateEngine.makeTemplateSource.addTemplate("ko_simplegrid_pagelinks", "\
//                    <div class=\"ko-grid-pagelinks\">\
//                        <span>page:</span>\
//                        {{each(i) ko.utils.range(1, 100)}}\
//                            <span>\
//                                ${{i}}()\
//                            </span>\
//                        {{/each}}\
//                    </div>");

//ko.setTemplateEngine(templateEngine);



//-----------------------------------------------------------------------------------------------

//(function () {
//    // Private function
//    function getColumnsForScaffolding(data) {
//        if ((typeof data.length != 'number') || data.length == 0)
//            return [];
//        var columns = [];
//        for (var propertyName in data[0])
//            columns.push({ headerText: propertyName, rowText: propertyName });
//        return columns;
//    }

//    ko.simpleGrid = {
//        // Defines a view model class you can use to populate a grid
//        viewModel: function (configuration) {
//            this.data = configuration.data;
//            this.currentPageIndex = ko.observable(0);
//            this.pageSize = configuration.pageSize || 5;

//            // If you don't specify columns configuration, we'll use scaffolding
//            this.columns = configuration.columns || getColumnsForScaffolding(ko.utils.unwrapObservable(this.data));

//            this.itemsOnCurrentPage = ko.dependentObservable(function () {
//                var startIndex = this.pageSize * this.currentPageIndex();
//                return this.data.slice(startIndex, startIndex + this.pageSize);
//            }, this);

//            this.maxPageIndex = ko.dependentObservable(function () {
//                return Math.ceil(ko.utils.unwrapObservable(this.data).length / this.pageSize);
//            }, this);
//        }
//    };

//    // Templates used to render the grid
//    var templateEngine = new ko.jqueryTmplTemplateEngine();
//    templateEngine.addTemplate("ko_simpleGrid_pageLinks", "\
//                    <div class=\"ko-grid-pageLinks\">\
//                        <span>Page:</span>\
//                        {{each(i) ko.utils.range(1, maxPageIndex)}}\
//                            <a href=\"#\" data-bind=\"click: function() { currentPageIndex(i) }, css: { selected: i == currentPageIndex() }\">\
//                                ${ i + 1 }\
//                            </a>\
//                        {{/each}}\
//                    </div>");

//    // The "simpleGrid" binding
//    ko.bindingHandlers.pager = {
//        // This method is called to initialize the node, and will also be called again if you change what the grid is bound to
//        update: function (element, viewModelAccessor, allBindingsAccessor) {
//            var viewModel = viewModelAccessor(), allBindings = allBindingsAccessor();

//            // Empty the element
//            while (element.firstChild)
//                ko.removeNode(element.firstChild);

//            // Allow the default templates to be overridden
//            var pageLinksTemplateName = allBindings.simpleGridPagerTemplate || "ko_simpleGrid_pageLinks";

//            // Render the page links
//            var pageLinksContainer = element.appendChild(document.createElement("DIV"));
//            ko.renderTemplate(pageLinksTemplateName, viewModel, { templateEngine: templateEngine }, pageLinksContainer, "replaceNode");
//        }
//    };
//})();